package org.sws.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.sws.domain.strategy.enums.LogicModel;
import org.sws.domain.strategy.model.valobj.ChainStrategyAwardVO;
import org.sws.domain.strategy.repository.IStrategyRepository;
import org.sws.domain.strategy.service.armory.IStrategyDispatch;
import org.sws.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.sws.types.common.Constants;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author sws
 * @Date 2025/2/24 16:11
 * @description: 权重责任链节点
 */
@Slf4j
@Service("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;
    @Resource
    protected IStrategyDispatch strategyDispatch;
    @Override
    protected String ruleModel() {
        return LogicModel.RULE_WIGHT.getCode();
    }

    @Override
    public ChainStrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        // 获取rule_weight的 rulevalue
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());

        // 1. 根据用户ID查询用户抽奖消耗的积分值
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);
        if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) {
            log.warn("抽奖责任链-权重告警【策略配置权重，但ruleValue未配置相应值】 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
            return next().logic(userId, strategyId);
        }
        // 查询已抽奖次数
        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);
        // 将权重规则map进行排序，用于和用户积分进行比较，取小于用户积分的最大的权重规则
        ArrayList<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Long nextValue = analyticalSortedKeys.stream()
                .filter(analyticalSortedKeyValue -> analyticalSortedKeyValue <= userScore)
                .max(Comparator.naturalOrder()).orElse(null);

        log.info("用户积分:{} 权重规则:{} 规则值:{}", userScore, nextValue, analyticalValueGroup.get(nextValue));

        // 权重抽奖
        if (null != nextValue) {
            Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, ruleModel(), awardId);
            return ChainStrategyAwardVO.builder().logicModel(ruleModel()).awardId(awardId).build();
        }

        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId,strategyId);
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SEMICOLON);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            // 以每一组的：前的权重model为key，整个组为value
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }
}
